import { Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges } from '@angular/core';
import { ConfigModule } from '../../config.module';
import { FileUploader } from 'ng2-file-upload';
import { NzMessageService } from 'ng-zorro-antd/message';
import { environment } from '../../../environments/environment';

@Component({
    selector: 'app-import-button',
    templateUrl: './import-button.component.html',
    styleUrls: ['./import-button.component.scss']
})
export class ImportButtonComponent implements OnInit, OnChanges {
    @Input() fileType; //允许的文件类型
    @Input() acceptListLength; //允许导入的文件个数
    @Input() type: string; //选择的导入的类型
    @Input() importUrl: string; //导入接口URL
    @Input() toolTips: string; //鼠标提示文字
    @Output() importSuccessState: EventEmitter<any> = new EventEmitter<any>();
    uploadingState = false; //是否在上传进程中
    uploadValidState = true; //验证是否可以上传
    selectedFileLength = 0; //已选择的上传文件个数
    uploader: FileUploader; //导入组件实例
    uploadingStateText = '导入';
    constructor(private _nzMessageService: NzMessageService, public _config: ConfigModule) {
        this.importUrl = this.importUrl || this._config.importBaseUrl;
    }

    ngOnInit() {}

    ngOnChanges(changes: SimpleChanges) {
        this.uploader = new FileUploader({
            url: environment.baseUrl + this.importUrl,
            method: 'POST',
            itemAlias: 'file',
            autoUpload: false,
            parametersBeforeFiles: false,
            removeAfterUpload: true,
            headers: [{ name: 'token', value: sessionStorage.getItem('token') }]
        });

        //跨域和上传文件路径上传设置
        this.uploader.onAfterAddingFile = (item) => {
            item.withCredentials = false;
        };
    }

    /**
     * 开始上传文件
     */
    onUploadFile() {
        this.uploader.uploadAll();
        this.uploader.onSuccessItem = (item, res: any) => {
            if (JSON.parse(res).code === 200) {
                this._nzMessageService.create('success', JSON.parse(res).msg);
                this.importSuccessState.emit(200);
                this.uploadingStateText = '导入';
            } else {
                this._nzMessageService.create('error', JSON.parse(res).msg);
                this.uploadingStateText = '导入';
            }
        };
        this.uploader.onCompleteAll = () => {
            this.uploadingState = false;
        };
    }

    /**
     * 选择文件
     * @param ev 选择的文件对象
     */
    onSelectedFileChanged(ev) {
        const _this = this;
        const selectedArr: Array<any> = [];
        const totalFileLength = selectedArr.length + this.uploader.queue.length; //获取上传文件的总数
        this.uploader.queue.forEach((item, index) => {
            if (this.selectedFileLength === 0 || index > this.selectedFileLength - 1) {
                const reader = new FileReader();
                reader.onload = function () {
                    const imgs = {
                        url: this.result,
                        uploadID: index,
                        pIndex: index
                    };
                    if (selectedArr.length > 0) {
                        let isSame = false;
                        selectedArr.forEach((img, j) => {
                            if (img.url === this.result) {
                                isSame = true;
                            }
                        });
                        if (!isSame) {
                            selectedArr.push(imgs);
                        } else {
                            _this.uploader.queue[index].remove(); //如果已经选择，就需要在队列中移除该图片
                            _this.selectedFileLength = _this.uploader.queue.length; //并更新已选图片数量
                        }
                    } else {
                        selectedArr.push(imgs);
                    }
                };
            }
            const extension = item.file.name.substring(item.file.name.lastIndexOf('.') + 1, item.file.name.length);
            if (this.fileType !== undefined) {
                //已配置上传类型
                if (!this.fileType.includes(extension)) {
                    //上传文件中有不符条件的文件类型
                    this.uploadValidState = false;
                    this._nzMessageService.create('warning', `上传的格式仅支持${this.fileType}`);
                    this.uploader.queue.length = 0;
                } else if (totalFileLength > this.acceptListLength) {
                    //判断上传文件的总数
                    this._nzMessageService.create('warning', `最多能上传${this.acceptListLength}张图片`);
                    this.uploader.queue.length = 0;
                    this.uploadValidState = false;
                } else {
                    this.uploadValidState = true;
                    this.uploadingStateText = '导入中';
                }
            } else {
                //未配置上传类型
                this.uploadValidState = false;
                this.uploader.queue.length = 0;
                this._nzMessageService.create('warning', '请在组件中配置上传文件类型');
            }
        });

        /**
         * 上传的文件类型通过验证
         */
        if (this.uploadValidState) {
            this.selectedFileLength = this.uploader.queue.length;
            this.onUploadFile();
            this.uploadingState = true;
        }
    }
}
